package com.cx.design_pattern.createMode.general;


import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

interface Phone {

    abstract void brand();

}

class PhoneNamedHuawei implements Phone {

    @Override
    public void brand() {

        System.out.println("华为");

    }

}

class PhoneNamedXiaomi implements Phone {

    @Override
    public void brand() {

        System.out.println("小米");

    }

}

class PhoneNamedVivo implements Phone {

    @Override
    public void brand() {

        System.out.println("vivo");

    }

}

class PhoneFactory {

    private static Properties env = new Properties();

    //在类加载时就完成流操作
    static {

        try {

            InputStream input = PhoneFactory.class.getClassLoader().getResourceAsStream("/factory.properties");
            env.load(input);
            input.close();
        } catch (IOException e) {

            e.printStackTrace();

        }

    }

    public static Phone getPhone(String phoneName) {
        Phone phone = null;

        try {

            Class clazz = Class.forName(env.getProperty(phoneName));

            phone = (Phone) clazz.newInstance();

        } catch (ClassNotFoundException e) {

            e.printStackTrace();

        } catch (InstantiationException e) {

            e.printStackTrace();

        } catch (IllegalAccessException e) {

            e.printStackTrace();

        }

        return phone;
    }

}


public class FactoryBuilder {

    public static void main(String[] args) {
//创建小米手机
        Phone xiaomi = PhoneFactory.getPhone("小米");
        xiaomi.brand();
//创建华为手机
        Phone huawei = PhoneFactory.getPhone("华为");
        huawei.brand();
    }
}

